/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;

/**
 * @author joppe
 * 
 */
public class ListChaptersActivity extends LoggedActivity {
    // Option items.
    private static final int CREATE_QUIZ = 0;
    private static final int ADD_CHAPTER = 1;
    private static final int DELETE_CHAPTERS = 2;

    // Dialog identifiers.
    private static final int CREATE_QUIZ_DLG = 0;
    private static final int DELETE_CHAPTERS_DLG = 2;

    private Long mBookId = null;
    private VocabTutor mApplication = null;
    private Cursor mChaptersCursor = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        Bundle extraInfo = getIntent().getExtras();
        if (extraInfo != null) {
            mBookId = extraInfo.getLong("book_id");
        }
        else {
            Log.w("no_extra_info",
                    "ListChaptersActivity created with no book_id!");
        }
        setContentView(R.layout.chapter_list);
        ListView chapterList = (ListView) findViewById(R.id.chapter_list);
        chapterList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    public boolean onItemLongClick(AdapterView<?> chapterList,
                            View item, int position, long rowid) {
                        Log.d("com.joppe.vocabtutor", "Chapter long-clicked: "
                                + chapterList.getItemAtPosition(position));
                        Intent i = new Intent(ListChaptersActivity.this,
                                ListWordsActivity.class);
                        i.putExtra("book_id", mBookId);
                        i.putExtra("chapter_id", rowid);
                        startActivity(i);
                        return false;
                    }
                });
        SQLiteDatabase db = mApplication.getDataHelper().getReadableDatabase();
        LayoutInflater inflater = LayoutInflater.from(this);
        View header = inflater.inflate(R.layout.list_header, chapterList, false);
        chapterList.addHeaderView(header);
        // Set the book title in the header.
        TextView bookTitle = (TextView) findViewById(R.id.book_title);
        Cursor c = null;
        try {
            c = db.rawQuery("select title from books where _id = ?",
                    new String[] { mBookId.toString() });
            if (c.moveToFirst())
                bookTitle.setText(c.getString(0));
        }
        finally {
            if (c != null)
                c.close();
        }
        mChaptersCursor = db.query("chapters left join words on words.chapter_fk = chapters._id",
                        new String[] { "chapters._id as _id", "chapters.title", "count(words._id)" },
                        "chapters.book_fk = ?", new String[] { mBookId.toString() },
                        "chapters._id", null, null);
        ChapterListCursorListAdapter ca = new ChapterListCursorListAdapter(
                this, mChaptersCursor);
        chapterList.setAdapter(ca);
    }
    
    @Override
    public void onResume() {
        super.onResume();
        if (mChaptersCursor != null)
            mChaptersCursor.requery();
    }
    
    @Override
    public void onStop() {
        super.onStop();
        mChaptersCursor.deactivate();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mChaptersCursor.close();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, CREATE_QUIZ, Menu.NONE, "Generate new quiz");
        menu.add(Menu.NONE, ADD_CHAPTER, Menu.NONE, "Add new chapter");
        menu.add(Menu.NONE, DELETE_CHAPTERS, Menu.NONE, "Delete chapters");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case CREATE_QUIZ: {
            ListView chapterList = (ListView) findViewById(R.id.chapter_list);
            long[] checkedChapters = chapterList.getCheckItemIds();
            Intent i = new Intent(this, WordQuizActivity.class);
            i.putExtra("chapter_ids", checkedChapters);
            startActivity(i);
            return true;
        }
        case ADD_CHAPTER:
            Intent i = new Intent(this, CreateChapterActivity.class);
            i.putExtra("book_id", mBookId);
            startActivity(i);
            return true;
        case DELETE_CHAPTERS:
            showDialog(DELETE_CHAPTERS_DLG);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DELETE_CHAPTERS_DLG: {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete chapters");
            builder.setMessage("Temp message");
            builder.setPositiveButton("Delete",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ListView chapterList = (ListView) findViewById(R.id.chapter_list);
                            long[] selectedIds = chapterList.getCheckItemIds();
                            String selectString = VocabTutor
                                    .toCommaSeparatedString(selectedIds);
                            SQLiteDatabase db = null;
                            try {
                                db = mApplication.getDataHelper()
                                        .getWritableDatabase();
                                db.delete("chapters", "_id in " + selectString,
                                        null);
                                mChaptersCursor.requery();
                            }
                            catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    });
            builder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.i("event_notification",
                                    "Chapter deletion cancelled");
                        }
                    });
            return builder.create();
        }
        }
        return super.onCreateDialog(id);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DELETE_CHAPTERS_DLG: {
            AlertDialog ad = (AlertDialog) dialog;
            ListView chapterList = (ListView) findViewById(R.id.chapter_list);
            long[] selectedIds = chapterList.getCheckItemIds();
            String selectString = VocabTutor
                    .toCommaSeparatedString(selectedIds);
            SQLiteDatabase db = null;
            Cursor c = null;
            try {
                db = mApplication.getDataHelper().getWritableDatabase();
                c = db.query("chapters", new String[] { "title" }, "_id in "
                        + selectString, null, null, null, null);
                StringBuilder buf = new StringBuilder(
                        "Are you sure you want to delete the following chapters?");
                while (c.moveToNext()) {
                    buf.append('\n').append(c.getString(0));
                }
                ad.setMessage(buf.toString());
            }
            catch (Throwable t) {
                t.printStackTrace();
            }
            finally {
                if (c != null)
                    c.close();
            }
            break;
        }
        }
        super.onPrepareDialog(id, dialog);
    }
}
